//
//  ShakeActionController.swift
//  FunSeeker
//
//  Created by 王泽宇 on 2017/3/29.
//  Copyright © 2017年 edu.Tongji.sse. All rights reserved.
//

import UIKit

class ShakeActionController: UIViewController, UIViewControllerTransitioningDelegate, MoreControllerDelegate, AMapLocationManagerDelegate, MAMapViewDelegate, AMapSearchDelegate, AMapNearbySearchManagerDelegate{
    var text = ""
    var actName = ""
    var mapView : MAMapView?
    var locationManager = AMapLocationManager()
    var selfAnnotation : MAPointAnnotation?
    var search : AMapSearchAPI?
    var itemOffset = 0

    @IBOutlet weak var itemImage: UIImageView!
    @IBOutlet weak var itemLabel: UILabel!
    @IBOutlet weak var shakeButton: UIButton!
    
    override func viewDidLoad() {
        super.viewDidLoad()
        // Do any additional setup after loading the view.
        setupUI()
    }
    
    func configMapView() {
        let selfFrame = self.view.frame
        let yOffset = itemLabel.frame.origin.y+itemLabel.frame.height+28+(self.navigationController?.navigationBar.frame.height)!
        let mapFrame = CGRect(x: 0, y: yOffset, width: selfFrame.width, height: selfFrame.height-yOffset)
        mapView = MAMapView(frame: mapFrame)
        mapView?.delegate = self
        mapView?.showsCompass = false
        mapView?.showsScale = false
        search = AMapSearchAPI()
        search?.delegate = self
        locationManager.delegate = self
        locationManager.locatingWithReGeocode = true
        self.view.addSubview(mapView!)
        self.view.sendSubview(toBack: mapView!)
        locationManager.startUpdatingLocation()
    }
    
    func setupUI() {
        itemImage.image = UIImage(named: actName)
        itemLabel.text = text
        configMapView()
        shakeButton.layer.shadowOpacity = 0.8
        shakeButton.layer.shadowColor = UIColor.black.cgColor
        shakeButton.layer.shadowOffset = CGSize(width: 2, height: 2)
        let back = UIBarButtonItem(title: "", style: .done, target: nil, action: nil)
        self.navigationItem.backBarButtonItem = back
        self.navigationItem.title = "摇一摇"
    }
    
    func doShake() {
        if let ccc = selfAnnotation {
        }else{
            return
        }
        let request = AMapPOIAroundSearchRequest()
        let gp = AMapGeoPoint()
        gp.latitude = CGFloat((selfAnnotation?.coordinate.latitude)!)
        gp.longitude = CGFloat((selfAnnotation?.coordinate.longitude)!)
        request.location = gp
        request.keywords = text
        request.radius = 5000
        request.requireExtension = true
        request.sortrule = 0
        search?.aMapPOIAroundSearch(request)
    }
    
    @IBAction func shake(_ sender: UIButton) {
        doShake()
    }
    
    @IBAction func moreItem(_ sender: UIButton) {
        let moreVC = UIStoryboard(name: "Main", bundle: nil).instantiateViewController(withIdentifier: "MoreController") as! MoreController
        moreVC.delegate = self
        moreVC.transitioningDelegate = self
        moreVC.modalPresentationStyle = .custom
        self.present(moreVC, animated: true, completion: nil)
    }
    
    func getChosenItem(text: String, actName: String) {
        self.actName = actName
        self.text = text
        itemLabel.text = text
        itemImage.image = UIImage(named: actName)
    }

    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
        // Dispose of any resources that can be recreated.
    }
    

    /*
    // MARK: - Navigation

    // In a storyboard-based application, you will often want to do a little preparation before navigation
    override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
        // Get the new view controller using segue.destinationViewController.
        // Pass the selected object to the new view controller.
    }
    */

    //MARK: - UIViewControllerTransitioningDelegate
    func animationController(forPresented presented: UIViewController, presenting: UIViewController, source: UIViewController) -> UIViewControllerAnimatedTransitioning? {
        return CustomerPresentingAnimator()
    }
    func animationController(forDismissed dismissed: UIViewController) -> UIViewControllerAnimatedTransitioning? {
        return CustomerDismissingAnimator()
    }
    
    //MARK: - AMapLocationManagerDelegate
    func amapLocationManager(_ manager: AMapLocationManager!, didUpdate location: CLLocation!) {
        var flag = false
        if let a = selfAnnotation {
        }else {
            selfAnnotation = MAPointAnnotation()
            flag = true
        }
        mapView?.removeAnnotation(selfAnnotation)
        selfAnnotation!.coordinate = location.coordinate
        mapView?.addAnnotation(selfAnnotation)
        if flag {
            mapView?.setCenter((selfAnnotation?.coordinate)!, animated: true)
        }
    }
    
    //MARK: - MAMapViewDelegate
    func mapView(_ mapView: MAMapView!, viewFor annotation: MAAnnotation!) -> MAAnnotationView! {
        var annoView: MAAnnotationView?
        if(annotation as? MAPointAnnotation == selfAnnotation){
            annoView = MAAnnotationView(annotation: annotation, reuseIdentifier: nil)
            annoView?.image = UIImage(named: "my_position")
            annoView?.frame = CGRect(x: 0, y: 0, width: 34, height: 55)
            
        }
        return annoView
    }
    
    //MARK: - Search
    func nextItem() {
        itemOffset = itemOffset + 1
    }
    
    func firstItem() {
        itemOffset = 0
    }
    
    func onPOISearchDone(_ request: AMapPOISearchBaseRequest!, response: AMapPOISearchResponse!) {
        let shakeDVC = UIStoryboard(name: "Main", bundle: nil).instantiateViewController(withIdentifier: "ShakeDetailController") as! ShakeDetailController
        shakeDVC.text = self.text
        shakeDVC.actName = self.actName
        shakeDVC.itemInfo = response.pois[itemOffset%response.count]
        shakeDVC.transitioningDelegate = self
        shakeDVC.modalPresentationStyle = .custom
        self.present(shakeDVC, animated: true, completion: nil)
    }
    
    //MARK: - shake related
    override func motionEnded(_ motion: UIEventSubtype, with event: UIEvent?) {
        doShake()
    }
    
    override func becomeFirstResponder() -> Bool {
        return true
    }
    
    override func viewWillAppear(_ animated: Bool) {
        self.resignFirstResponder()
        super.viewWillAppear(animated)
    }
}
